<template>
  <div class="project-detail-container">
    <el-page-header @back="goBack" content="项目详情" />
    
    <!-- 第一部分：项目概览 -->
    <el-card class="section-card overview-section">
      <div class="header-section">
        <div class="title-section">
          <h1 class="project-title">{{ project.projectName }}</h1>
          <div class="tags-group">
          <el-tag :type="getStatusTagType(project.status)" size="large">
            {{ project.status }}
          </el-tag>
          <el-tag type="success" size="large" >
            {{ project.projectDuration }}个月
          </el-tag>
          </div>
        </div>
        <el-divider />
        <div class="basic-info">
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">投资方：</span>
              <span class="info-value">{{ project.investor }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">产业类别：</span>
              <span class="info-value">{{ project.industryCategory }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">所属园区：</span>
              <span class="info-value">{{ project.parkName }}</span>
            </div>
          </div>
          <div class="project-description">
            <div class="description-item">
              <span class="info-label">项目简介：</span>
              <span class="description-content">{{ project.description || '暂无项目简介' }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 第二部分：操作按钮 -->
    <el-card class="section-card action-section">
      <div class="action-buttons">
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>编辑
        </el-button>
        <el-button type="info" @click="handleFollowUp">
          <el-icon><DocumentAdd /></el-icon>写跟进
        </el-button>
        <el-button type="success" @click="handleSignContract">
          <el-icon><Document /></el-icon>项目文件上传
        </el-button>
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </div>
    </el-card>

    <!-- 第三部分：简化后的选项卡 -->
    <el-card class="section-card tab-section">
      <div class="tab-container">
     <!-- 左侧选项卡内容 -->
     <div class="tab-content">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="项目信息" name="projectInfo">
          <div class="info-table">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="项目编号">{{ project.projectCode }}</el-descriptions-item>
              <el-descriptions-item label="项目类型">
                  <el-tag :type="project.projectType === 'rental' ? 'success' : 'primary'">
                      {{ project.projectType === 'rental' ? '租赁厂房' : '独立选址' }}
                  </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="计划总投资">{{ project.totalInvestment }}万元</el-descriptions-item>
              <el-descriptions-item label="固定资产总投资">{{ project.fixedAssetsInvestment || '-' }}万元</el-descriptions-item>
              <el-descriptions-item label="用地面积">{{ project.landArea }}亩</el-descriptions-item>
              <el-descriptions-item label="产值">{{ project.outputValue || '-' }}万元/年</el-descriptions-item>
              <el-descriptions-item label="纳税额">{{ project.taxRevenue || '-' }}万元/年</el-descriptions-item>
              <el-descriptions-item label="项目类型">{{ project.projectType }}</el-descriptions-item>
              <el-descriptions-item label="项目来源">{{ project.projectSource }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ project.contactPhone }}</el-descriptions-item>
              <el-descriptions-item label="跟进人">{{ project.follower }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
        <el-tab-pane label="投资方信息" name="investorInfo">
          <div class="info-table">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="企业名称">{{ project.investor }}</el-descriptions-item>
              <el-descriptions-item label="联系人">{{ project.contactPerson }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ project.contactPhone }}</el-descriptions-item>
              <el-descriptions-item label="联系地址">{{ project.address || '-' }}</el-descriptions-item>
              <el-descriptions-item label="企业简介">
                <p>{{ project.investorDescription || '暂无企业简介' }}</p>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>


        <el-tab-pane label="项目签约文件" name="projectFiles">
        <div class="document-management">
          <div class="header-section" style="display: flex; justify-content: space-between; margin-bottom: 30px;margin-top: 30px;">
              <h3 class="title" style="margin: 0; font-size: 18px; color: #333;"><el-icon style="color: black"><CollectionTag /></el-icon> 项目签约文档资料</h3>
            <div class="search-section" style="display: flex; align-items: center;">
              <el-input
              v-model="searchQuery"
              placeholder="请输入文件名称"
              clearable
             style="width: 200px; margin-right: 10px;"
              />
             <el-button type="primary">查询</el-button>
            </div>
          </div>
          
<!-- 文件列表表格 -->
<el-table 
  :data="paginatedFiles" 
  style="width: 100%; margin-top: 20px" 
  border
  :scroll-x="true"
  v-loading="loadingFiles"
>
  <el-table-column prop="index" label="序号" align="center" />
  <el-table-column label="文件名称" width="280" align="center">
    <template #default="{ row }">
      <div class="file-display">
        <el-link 
          type="primary" 
          @click="handlePreviewFile(row)"
          class="file-link"
        >
          {{ row.originalName }}
        </el-link>
      </div>
    </template>
  </el-table-column>
  <el-table-column prop="format" label="文件格式" width="100" align="center">
    <template #default="{ row }">
      <span class="file-format">{{ row.format }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="uploadTime" label="上传时间" width="250" align="center" />
  <el-table-column label="文件大小" width="120" align="center">
    <template #default="{ row }">
      <span>{{ formatFileSize(row.fileSize) }}</span>
    </template>
  </el-table-column>
  <el-table-column label="操作" width="180" align="center" fixed="right">
    <template #default="{ row }">
      <el-link type="primary" @click="handleDownloadFile(row)" style="margin-right: 10px;">下载</el-link>
      <el-link type="danger" @click="handleDeleteFile(row)">删除</el-link>
    </template>
  </el-table-column>
</el-table>

<!-- 分页组件 -->
<div class="pagination-section">
  <span class="total-text">共{{ filteredFiles.length }}条</span>
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :total="filteredFiles.length"
    :page-sizes="[5, 10, 20]"
    layout="prev, pager, next, sizes"
    background
  />
</div>
        </div>  
      </el-tab-pane>
      <el-tab-pane label="项目跟进记录" name="record">
  <div class="follow-up-list">
    <el-timeline>
      <el-timeline-item
        v-for="record in followRecords"
        :key="record.id"
        :timestamp="formatDate(record.followUpDate)"
        placement="top"
      >
        <el-card>
          <p class="follow-content">{{ record.followUpContent }}</p>
          <div class="follow-meta">
            <span>{{ record.followUpPerson }}</span>
            <span>{{ record.createdAt }}</span>
          </div>
        </el-card>
      </el-timeline-item>

      <el-timeline-item v-if="!followRecords.length">
        <el-card>
          <p class="no-data">暂无跟进记录</p>
        </el-card>
      </el-timeline-item>
    </el-timeline>
  </div>
</el-tab-pane>
      </el-tabs>
       </div>

  </div>
    </el-card>
  </div>

   <el-dialog v-model="uploadDialogVisible" title="上传项目文件" width="50%">
   <el-upload
        action="#"
        multiple
        :limit="5"
        :file-list="uploadFiles"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        drag
        :on-exceed="handleExceed"
        
    >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                拖拽文件到此处或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传文档、图片等附件，单个文件不超过10MB
              </div>
            </template>
    </el-upload>
  
  
  <template #footer>
    <el-button @click="uploadDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitUpload">确认上传</el-button>
  </template>
</el-dialog>

<el-dialog v-model="timelineEventsVisible" title="填写跟进记录" width="600px">
  <el-form :model="timelineEventsForm" label-width="100px">
    <el-form-item label="标题" required>
      <el-input v-model="timelineEventsForm.title" placeholder="请输入标题" />
    </el-form-item>
    <el-form-item label="跟进内容" required>
      <el-input
        v-model="timelineEventsForm.content"
        type="textarea"
        :rows="5"
        placeholder="请输入跟进内容"
        show-word-limit
        maxlength="500"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="timelineEventsVisible = false">取消</el-button>
    <el-button type="primary" @click="submitFollowUp">提交</el-button>
  </template>
</el-dialog>

<ProjectDialog
  v-model="editDialogVisible"
  dialog-type="edit"
  :current-project="project"
  @submit="handleProjectUpdate"
/>
</template>

<script setup>
import { ref, onMounted, computed,watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Edit, User, DocumentAdd, Document, Delete, CollectionTag, UploadFilled, Picture, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProjectDialog from './component/ProjectDialog.vue'
import { useProjectStore } from '@/stores/project'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const projectStore = useProjectStore()
const activeTab = ref('projectInfo')

// 项目数据
const project = ref({})
const followRecords = ref([])
const editDialogVisible = ref(false)

// 文件相关状态
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const projectFiles = ref([]) // 存储项目文件列表
const loadingFiles = ref(false)

// 上传相关状态
const uploadDialogVisible = ref(false)
const uploadFiles = ref([])

// 统一使用一个axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

// 加载项目详情和跟进记录
const loadProject = async () => {
  try {
    const { data } = await api.get(`/api/projects/${route.params.id}`)
    project.value = data

    const { data: list } = await api.get(`/api/projects/${route.params.id}/follow-ups`)
    followRecords.value = list
  } catch (error) {
    console.error('加载项目详情失败:', error)
    ElMessage.error('加载项目详情失败')
  }
}

// 加载项目文件
const loadProjectFiles = async () => {
  if (!project.value.id) return
  
  loadingFiles.value = true
  try {
    const response = await api.get(`/api/projects/${project.value.id}/files`)
    projectFiles.value = response.data
    console.log('加载项目文件成功:', projectFiles.value)
  } catch (error) {
    console.error('加载项目文件失败:', error)
    ElMessage.error('加载项目文件失败')
  } finally {
    loadingFiles.value = false
  }
}

// 删除项目文件
const handleDeleteFile = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件 "${file.originalName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除文件接口
    await api.delete(`/api/projects/${project.value.id}/files/${file.id}`)
    ElMessage.success('文件删除成功')
    
    // 重新加载文件列表
    await loadProjectFiles()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文件失败:', error)
      ElMessage.error('删除文件失败')
    }
  }
}

// 下载文件
const handleDownloadFile = async (file) => {
  try {
    // 如果是新上传但未保存的文件
    if (file.raw && !file.id) {
      const url = URL.createObjectURL(file.raw)
      const link = document.createElement('a')
      link.href = url
      link.download = file.originalName || file.name
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    } 
    // 如果是已保存的文件
    else if (file.id) {
      const downloadUrl = `${import.meta.env.VITE_API_BASE_URL}/api/projects/${project.value.id}/files/${file.id}/download`
      
      // 使用 fetch API 下载
      const response = await fetch(downloadUrl)
      if (!response.ok) {
        throw new Error('下载失败')
      }
      
      // 获取 blob 数据
      const blob = await response.blob()
      
      // 创建下载链接
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = file.originalName // 设置正确的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    } else {
      ElMessage.warning('文件无法下载，文件数据不存在')
      return
    }
    
    ElMessage.success(`文件 ${file.originalName} 开始下载`)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}
// 预览文件
const handlePreviewFile = (file) => {
  // 这里可以根据文件类型实现不同的预览方式
  ElMessage.info(`预览文件: ${file.originalName}`)
  // 实际项目中可以打开新窗口预览PDF、图片等
}

// 上传文件
const submitUpload = async () => {
  if (uploadFiles.value.length === 0) {
    ElMessage.warning('请先上传文件')
    return
  }

  try {
    // 为每个文件创建FormData并上传
    const uploadPromises = uploadFiles.value.map(async (file) => {
      const formData = new FormData()
      formData.append('file', file.raw)
      formData.append('projectId', project.value.id)
      formData.append('description', '项目文件')
      formData.append('category', 'document')
      formData.append('uploaderName', '当前用户') // 实际项目中应该从用户信息获取

      return await api.post(`/projects/${project.value.id}/files`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    })

    // 等待所有文件上传完成
    await Promise.all(uploadPromises)
    
    ElMessage.success(`成功上传 ${uploadFiles.value.length} 个文件`)
    uploadDialogVisible.value = false
    uploadFiles.value = []
    
    // 重新加载文件列表
    await loadProjectFiles()
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')
  }
}

// 文件列表数据
const fileList = computed(() => {
  return projectFiles.value.map((file, index) => {
    const format = file.fileType ? file.fileType.toUpperCase() : 'FILE'
    return {
      ...file,
      index: index + 1,
      name: file.originalName,
      format: format,
      uploadTime: file.createdAt ? new Date(file.createdAt).toLocaleString() : '-'
    }
  })
})
// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
// 过滤后的文件列表
const filteredFiles = computed(() => {
  let result = fileList.value
  if (searchQuery.value) {
    result = result.filter(file => 
      file.originalName.includes(searchQuery.value)
    )
  }
  return result
})

// 分页后的文件列表
const paginatedFiles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredFiles.value.slice(start, end)
})


const getStatusTagType = (status) => {
  const map = {
    '在谈': 'primary',
    '已签约': 'success', 
    '建设中': 'warning',
    '竣工验收': 'info',
    '审核中': '',
    '主任办公室': 'warning'
  }
  return map[status] || 'info'
}

const goBack = () => {
  router.go(-1)
}

const handleEdit = () => {
  if (!project.value.id) {
    ElMessage.error('项目ID不存在')
    return
  }
  
  console.log('跳转到编辑页面，项目ID:', project.value.id)
  router.push({
    name: 'ProjectEdit',
    query: {
      id: project.value.id
    }
  })
}

const handleFollowUp = () => {
  router.push({ 
    name: 'ProjectFollowUp',
    query: {
      id: project.value.id
    }
  })
}

const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  const today = new Date()
  
  if (date.toDateString() === today.toDateString()) {
    return '今天'
  }
  
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天'
  }
  
  return dateStr
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目【${project.value.projectName}】吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/api/projects/${project.value.id}`)
    ElMessage.success('项目已删除')
    router.go(-1)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

// 文件上传处理
const handleSignContract = () => {
  uploadFiles.value = []
  uploadDialogVisible.value = true
}

const handleFileChange = (file, fileList) => {
  const isDuplicate = fileList.some(f => 
    f.name === file.name && 
    f.uid !== file.uid
  )

  if (isDuplicate) {
    ElMessage.error({
      message: `文件 "${file.name}" 已存在，请勿重复选择`,
      duration: 3000,
      showClose: true
    })
    return false
  }
  uploadFiles.value = fileList
}

const handleFileRemove = (file, fileList) => {
  uploadFiles.value = fileList
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}



onMounted(() => {
  loadProject()
  // 监听标签页变化

watch(activeTab, (newTab) => {
  if (newTab === 'projectFiles' && project.value.id) {
    loadProjectFiles()
  }
})
})
</script>

<style scoped>
/* 右上标签 */
.tags-group {
  display: flex;
  gap: 10px; 
  margin-left: 10px; /* 与项目名称保持一定距离 */
}
.project-detail-container {
  padding: 20px;
}

.section-card {
  margin-top:20px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.overview-section {
  .header-section {
    .title-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .project-title {
        margin: 0;
        font-size: 24px;
        color: #333;
      }
    }
    
    .basic-info {
      .info-row {
        display: flex;
        flex-wrap: wrap;
        gap: 30px;
        margin-bottom: 20px;
        
        .info-item {
          .info-label {
            font-weight: bold;
            color: #666;
          }
          
          .info-value {
            color: #333;
          }
        }
      }
      
      .project-description {
        h3 {
          margin: 20px 0 10px;
          color: #333;
        }
        
        p {
          color: #666;
          line-height: 1.6;
        }
      }
    }
  }
}

.action-section {
  .action-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    
    .el-button {
      flex: 1;
      min-width: 120px;
    }
  }
}

.tab-section {
  :deep(.el-tabs__header) {
    margin: 0;
  }
  
  :deep(.el-tabs__item) {
    font-size: 16px;
    height: 50px;
    line-height: 50px;
  }
  
  .info-table {
    padding: 10px;
    
    :deep(.el-descriptions__body) {
      background-color: #fafafa;
    }
  }
}
.project-description {
  margin-top: 20px;
}

.description-item {
  display: flex;
  align-items: flex-start;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 80px; /* 保持与上方标签对齐 */
  margin-right: 10px;
}

.description-content {
  color: #333;
  text-align: left;
  white-space: pre-line; /* 保留换行符 */
  word-break: break-word; /* 长单词换行 */
  width: 100%;
}
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}
.upload-demo {
  margin-top: 15px;
}

.uploaded-files {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.file-list-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.file-info {
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 8px;
  color: #409EFF;
}

.file-name {
  font-size: 14px;
  color: #333;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.success-icon {
  color: #67C23A;
  font-size: 18px;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.follow-up-list {
  padding: 10px 0;
}
.follow-content {
  line-height: 1.6;
  white-space: pre-line;
}
.follow-meta {
  margin-top: 10px;
  font-size: 12px;
  color: #888;
  display: flex;
  justify-content: space-between;
}
.no-data {
  color: #999;
  text-align: center;
  padding: 20px 0;
}
</style>